﻿using Api.Application.Command.Menu;
using AutoMapper;
using Domain;
using ErrorCode;
using Infrastructure;
using MediatR;

namespace Api.Application.Handler.Menu
{
    public class AddMenuHandler : IRequestHandler<AddMenuCommand, ApiResult<int>>
    {
        private readonly IBase<MenuModel> menuRepo;
        private readonly IMapper mapper;

        public AddMenuHandler(IBase<MenuModel> menuRepo,IMapper mapper)
        {
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(AddMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var menu = mapper.Map<MenuModel>(request);
            var model = menuRepo.GetAll().Where(x => x.MenuName == request.MenuName && !x.IsDeleted).Count();
            if (model > 0)
            {
                result.Code = ApiEnum.Fail;
                result.Msg = "菜单名称已存在";
                return Task.FromResult(result);
            }
            menu.CrearName = "张三";
            menu.CrearTime= DateTime.Now;
            menu.UpdateName = "";
            menu.UpdateTime = null;
            var r=menuRepo.Add(menu).Result;
            if (r > 0)
            {
                result.Code = ApiEnum.OK;
                result.Data = r;
                result.Msg = "菜单添加成功";
            }
            else
            {
                result.Code = ApiEnum.Fail;
                result.Data = r;
                result.Msg = "菜单添加失败";
            }
            return Task.FromResult(result);
            
            
        }
    }
}
